
//
//  JSTFeedBackViewController.m
//  KYKJPackDemo
//
//  Created by 01 on 2017/9/14.
//  Copyright © 2017年 ???. All rights reserved.
//

#import "JSTFeedBackViewController.h"
#import "ZYQAssetPickerController.h"

#define ImageWidth      ((kDeviceWidth - kCurrentScreenWidth(15))/3. - kCurrentScreenWidth(15))

typedef void (^DeteleImageBlock)(id sender);
@interface JSTFeedBackViewController ()<UITextViewDelegate, UIActionSheetDelegate, ZYQAssetPickerControllerDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (nonatomic, strong) UITextView *textView;

@property (nonatomic, strong) UIButton *submitBtn;

@property (nonatomic, strong) UILabel *placeLabel;

@property (nonatomic, strong) UILabel *numLabel;

@property (nonatomic, strong) UIButton *postBtn;

@property (nonatomic, strong) UIView *backView;

@property (nonatomic, strong) NSMutableArray *imageArray;

@property (nonatomic, strong) UIImageView *imageview;

@property(nonatomic,copy)   SNBasicBlock selectedReasonBlock;
@property(nonatomic,copy)   SNBasicBlock postImageBtnBlock;
@property(nonatomic,copy)   DeteleImageBlock deteleImageBtnBlock;

@end

@implementation JSTFeedBackViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"意见反馈";
    self.view.backgroundColor = kWhiteColor;
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self createContent];
}

- (void) createContent
{
    _imageArray = [NSMutableArray array];
    
    [self.view addSubview:self.textView];
    [self.view addSubview:self.numLabel];
    [self.view addSubview:self.backView];
    [self.view addSubview:self.submitBtn];
    
}

#pragma mark  ---- 事件
- (void) submitFeedBack
{
    
}

- (void) refreshImage
{
    for (UIView *obj in self.backView.subviews)
    {
        if (obj != self.postBtn)
        {
            [obj removeFromSuperview];
        }
    }
    [_imageArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIImage *image=(UIImage *)obj;
        
        _imageview = [[UIImageView alloc] initWithFrame:CGRectMake(kCurrentScreenWidth(15) + idx*(ImageWidth + kCurrentScreenWidth(15)), 0, ImageWidth, ImageWidth)];
        _imageview.userInteractionEnabled = YES;
        _imageview.contentMode = UIViewContentModeScaleAspectFill;
        _imageview.clipsToBounds = YES;
        _imageview.tag = idx+1;
        _imageview.image = image;
        [self.backView addSubview:_imageview];
        
        UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        deleteBtn.frame = CGRectMake((idx+1)*(ImageWidth + kCurrentScreenWidth(15)) - kCurrentScreenWidth(10), _imageview.top-kCurrentScreenWidth(10), kCurrentScreenWidth(20), kCurrentScreenWidth(20));
        [deleteBtn setImage:[UIImage imageNamed:@"eva_delete"] forState:UIControlStateNormal];
        deleteBtn.tag = idx+10;
        [deleteBtn addTarget:self action:@selector(deleteImage:) forControlEvents:UIControlEventTouchUpInside];
        [self.backView addSubview:deleteBtn];
    }];
    
    if (_imageArray.count > 0)
    {
        self.postBtn.frame = CGRectMake(CGRectGetMaxX(_imageview.frame) + kCurrentScreenWidth(15), 0, kCurrentScreenWidth(84), kCurrentScreenWidth(84));
    } else
    {
        self.postBtn.frame = CGRectMake(10, 0, kCurrentScreenWidth(84), kCurrentScreenWidth(84));
    }
    
    if (_imageArray.count >= 3)
    {
        self.postBtn.hidden = YES;
    }
    else
    {
        self.postBtn.hidden = NO;
    }
}

- (void)deleteImage:(UIButton *)sender
{
    UIButton *button = (UIButton *)sender;
    DLog(@"button===%zd==",button.tag);
    [_imageArray removeObjectAtIndex:button.tag-10];
    [self refreshImage];
}

- (void)postImage
{
    [self.textView resignFirstResponder];
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册选择", nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [actionSheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        //访问相机
        UIImagePickerControllerSourceType sourceType=UIImagePickerControllerSourceTypeCamera;
        
        UIImagePickerController *imagePickerController=[[UIImagePickerController alloc] init];
        
        imagePickerController.modalTransitionStyle=UIModalTransitionStyleCoverVertical;
        
        imagePickerController.delegate=self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType=sourceType;
        
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }else if (buttonIndex == 1)
    {
        //访问相册
        ZYQAssetPickerController *picker = [[ZYQAssetPickerController alloc] init];
        picker.maximumNumberOfSelection = 3;
        picker.assetsFilter = [ALAssetsFilter allPhotos];
        picker.showEmptyGroups=NO;
        picker.delegate=self;
        picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
            if ([[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo]) {
                NSTimeInterval duration = [[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
                return duration >= 5;
            } else {
                return YES;
            }
        }];
        
        [self presentViewController:picker animated:YES completion:NULL];
    }else
    {
        return;
    }
}

#pragma mark - ZYQAssetPickerController Delegate
-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    NSMutableArray *array = [NSMutableArray array];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            
        });
        for (int i = 0; i < assets.count; i++) {
            ALAsset *asset = assets[i];
            
            UIImage *tempImg=[UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
            [array addObject:tempImg];
            //回到主线程
            dispatch_async(dispatch_get_main_queue(), ^{
                if (i==assets.count-1) {
                    
                    if (_imageArray.count+array.count <= 3) {
                        [_imageArray addObjectsFromArray:array];
                    }else{
                        JSTAlertView *angAlertView = [[JSTAlertView alloc] initWithTitle:@"提示" message:@"最多上传三张图片" customView:nil delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil];
                        [angAlertView show];
                        return ;
                    }
                    [self refreshImage];
                }
            });
        }
    });
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
#pragma mark imagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image=[info valueForKey:UIImagePickerControllerEditedImage];
    
    [_imageArray addObject:image];
    
    if (_imageArray.count > 3) {
        
        [self dismissViewControllerAnimated:YES completion:nil];
        JSTAlertView *angAlertView = [[JSTAlertView alloc] initWithTitle:@"提示" message:@"最多上传三张图片" customView:nil delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil];
        [angAlertView show];
        return;
    }
    [self setImageArray:_imageArray];
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark  ---- textViewDelegate
- (void)textViewDidChange:(UITextView *)textView
{
    if (IsStrEmpty(textView.text))
    {
        _placeLabel.hidden = NO;
    } else {
        _placeLabel.hidden = YES;
        if (textView.text.length > 200) {
            self.numLabel.textColor = [UIColor redColor];
        }else
        {
            self.numLabel.textColor = [UIColor grayColor];
        }
    }
    self.numLabel.text = [NSString stringWithFormat:@"%ld", 200 - textView.text.length];
}

#pragma mark  ---- 试图实例
- (UITextView *)textView
{
    if (!_textView) {
        _textView = [[UITextView alloc] initWithFrame:CGRectMake(kCurrentScreenWidth(10), kCurrentScreenWidth(10) + kNavBarHeight, kDeviceWidth - kCurrentScreenWidth(10*2), kCurrentScreenWidth(200))];
        _textView.backgroundColor = kWhiteColor;
        _textView.layer.cornerRadius = kCurrentScreenWidth(4);
        _textView.layer.borderWidth = 0.5;
        _textView.layer.borderColor = kSPSeparateLineColor.CGColor;
        _textView.font = kSystemFont(kCurrentScreenWidth(13));
        _textView.delegate = self;
//        [_textView scrollRangeToVisible:NSMakeRange(0, 1)];
        
        _placeLabel = [[UILabel alloc] initWithFrame:CGRectMake(kCurrentScreenWidth(5), kCurrentScreenWidth(5), _textView.frame.size.width-kCurrentScreenWidth(10), kCurrentScreenWidth(20))];
        _placeLabel.font = kSystemFont(kCurrentScreenWidth(13));
        _placeLabel.numberOfLines = 0;
        _placeLabel.textColor = kSPGrayTextColor;
        _placeLabel.text = @"请将您遇到的问题反馈我们";
        [_textView addSubview:_placeLabel];
    }
    return _textView;
}

- (UILabel *)numLabel
{
    if (!_numLabel) {
        _numLabel = [[UILabel alloc] initWithFrame:CGRectMake(kCurrentScreenWidth(10), CGRectGetMaxY(self.textView.frame) + kCurrentScreenWidth(5), kDeviceWidth - kCurrentScreenWidth(10)*2, kCurrentScreenWidth(25))];
        _numLabel.textColor = [UIColor grayColor];
        _numLabel.text = @"200";
        _numLabel.textAlignment = NSTextAlignmentRight;
    }
    return _numLabel;
}

- (UIButton *)postBtn
{
    if (!_postBtn) {
        _postBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _postBtn.frame = CGRectMake(kCurrentScreenWidth(10), 0, kCurrentScreenWidth(84), kCurrentScreenWidth(84));
        [_postBtn setImage:[UIImage imageNamed:@"refund_upload"] forState:UIControlStateNormal];
        [_postBtn addTarget:self action:@selector(postImage) forControlEvents:UIControlEventTouchUpInside];
    }
    return _postBtn;
}

- (UIView *)backView
{
    if (!_backView) {
        _backView = [[UIView alloc] initWithFrame:CGRectMake(0, self.numLabel.bottom+kCurrentScreenWidth(10), kDeviceWidth, kCurrentScreenWidth(84))];
        
        [_backView addSubview:self.postBtn];
    }
    return _backView;
}

- (UIButton *)submitBtn
{
    if (!_submitBtn) {
        _submitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _submitBtn.frame = CGRectMake(kCurrentScreenWidth(50), CGRectGetMaxY(self.backView.frame) + kCurrentScreenWidth(30), kDeviceWidth - kCurrentScreenWidth(50)*2, kCurrentScreenWidth(35));
        _submitBtn.layer.cornerRadius = kCurrentScreenWidth(5);
        [_submitBtn setBackgroundColor:kRedColor];
        [_submitBtn setTitle:@"提 交" forState:UIControlStateNormal];
        [_submitBtn addTarget:self action:@selector(submitFeedBack) forControlEvents:UIControlEventTouchUpInside];
    }
    return _submitBtn;
}
@end
